//
//  NSDictionary+Extension.m
//  Tools
//
//  Created by xlz on 2018/5/12.
//  Copyright © 2018年 com.365hy. All rights reserved.
//

#import "NSDictionary+Extension.h"

@implementation NSDictionary (Extension)

#pragma mark - 字典 转 json字符串
- (NSString *)wd_toJsonString {
    if ([NSJSONSerialization isValidJSONObject:self]) {
        NSError *error = nil;
        // 1.转化为 JSON 格式的 NSData
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self options:NSJSONWritingPrettyPrinted error:&error];
        if (error) {
            NSLog(@"字典转JSON字符串失败：%@", error);
        }
        // 2.转化为 JSON 格式的 NSString
        return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    return nil;
}

#pragma mark - 把字典拼成url字符串
- (NSString *)wd_toURLString {
    NSMutableString *mutableStr = [NSMutableString string];
    // 遍历字典把键值拼起来
    [self enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL *_Nonnull stop) {
        [mutableStr appendFormat:@"%@=", key];
        [mutableStr appendFormat:@"%@", obj];
        [mutableStr appendFormat:@"%@", @"&"];
    }];
    NSString *result = [mutableStr copy];
    // 去掉最后一个&
    if ([result hasSuffix:@"&"]) {
        result = [result substringToIndex:result.length - 2];
    }
    return result;
}

@end



@implementation NSMutableDictionary (Extension)

#pragma mark - 给可变字典添加键值对
- (void)wd_setObject:(id)anObject forKey:(id<NSCopying>)aKey {
    if (wd_isEmpty(aKey)) {
        return;
    }
    if (wd_isEmpty(anObject) && ![anObject isEqual:@""]) {
        return;
    }
    [self setObject:anObject forKey:aKey];
}

/** 判断对象是否为空 */
static inline BOOL wd_isEmpty(id thing) {
    return thing == nil ||
    [thing isEqual:[NSNull null]] ||
    [thing isEqual:@"null"] ||
    [thing isEqual:@"(null)"] ||
    ([thing respondsToSelector:@selector(length)]
     && [(NSData *)thing length] == 0) ||
    ([thing respondsToSelector:@selector(count)]
     && [(NSArray *)thing count] == 0);
}

@end
